<template>
  <div>
    <el-dialog
      :title="obj.isAdd ? '商品添加' : '商品编辑'"
      :visible.sync="obj.isTrue"
      width="50%"
      @close="cancel()"
      @opened="opened()"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="一级分类">
          <el-select
            v-model="form.first_cateid"
            placeholder="请选择一级分类"
            @change="changeFirst"
          >
            <el-option
              v-for="item in cateListData"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类">
          <el-select v-model="form.second_cateid" placeholder="请选择二级分类">
            <el-option
              v-for="item in secondArr"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="form.goodsname"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item label="市场价格">
          <el-input v-model="form.market_price"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <div class="imgFile">
            <h2>+</h2>
            <input type="file" @change="changeImg1" v-if="obj.isTrue" />
            <img :src="imgUrl" v-if="imgUrl" />
          </div>
        </el-form-item>
        <el-form-item label="商品规格">
          <el-select
            v-model="form.specsid"
            placeholder="请选择商品规格"
            @change="changeAttr"
          >
            <el-option
              v-for="item in specsListData"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格属性">
          <el-select
            v-model="form.specsattr"
            multiple
            placeholder="请选择规格属性"
          >
            <el-option
              v-for="(item, index) in secondAttr"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品">
          <el-radio :label="1" v-model="form.isnew">是</el-radio>
          <el-radio :label="2" v-model="form.isnew">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖">
          <el-radio :label="1" v-model="form.ishot">是</el-radio>
          <el-radio :label="2" v-model="form.ishot">否</el-radio>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
        <el-form-item label="商品描述">
          <div id="div1" v-if="obj.isTrue"></div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submit()" v-if="obj.isAdd">
          添 加</el-button
        >
        <el-button type="primary" @click="edit()" v-else>编 辑</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import { successAlert, warningAlert } from "../../../util/alert";
import { cateList, goodsAdd, goodsInfo, goodsEdit } from "../../../request/api";
import E from "wangeditor";
export default {
  props: ["obj"],
  components: {},
  data() {
    return {
      // 用来渲染图片路径
      imgUrl: "",
      // 用来渲染二级分类
      secondArr: [],
      // 用来渲染规格属性
      secondAttr: [],
      form: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 1,
        ishot: 1,
        status: 1,
      },
    };
  },
  computed: {
    ...mapGetters({
      cateListData: "cate/list",
      specsListData: "specs/list",
    }),
  },
  methods: {
    ...mapActions({
      reqCateList: "cate/reqChangeList",
      reqSpecsList: "specs/reqChangeList",
      reqGoodsList: "goods/reqChangeList",
      reqGoodsTotal: "goods/reqChangeTotal",
    }),
    // 对话框打开动画结束之后
    opened() {
      this.editor = new E("#div1");
      this.editor.create();
      // 给副文本编辑器设置内容
      this.editor.txt.html(this.form.description);
    },
    // 当一级分类发生变化时
    changeFirst() {
      cateList({ pid: this.form.first_cateid }).then((res) => {
        this.secondArr = res.data.list;
        // 清空原有的二级分类下拉框选中的内容
        this.form.second_cateid = "";
      });
    },
    // 当商品规格发生变化时
    changeAttr() {
      // 在所有数据中查找你需要的那一项
      let data = this.specsListData.find(
        (item) => item.id == this.form.specsid
      );
      // 把那一项中的attrs赋值给secondAttr
      this.secondAttr = data.attrs;
      // 要把原有选中的规格属性清空
      this.form.specsattr = "";
    },
    // 封装清空
    empty() {
      this.form = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 1,
        ishot: 1,
        status: 1,
      };
      this.imgUrl = "";
      this.secondArr = [];
      this.secondAttr = [];
    },
    // 点击了取消
    cancel() {
      // 关闭对话框并清空数据
      this.obj.isTrue = false;
      this.empty();
    },
    // 原生图片上传
    changeImg1(e) {
      // e.target.files[0] 图片所有信息
      let file = e.target.files[0];
      // 图片大小单位默认为B，   1024B=1KB      1024KB=1MG    1024MB=1GB
      if (file.size >= 2 * 1024 * 1024) {
        warningAlert("图片大小超出限制，请重新选择");
        return;
      }
      // URL.createObjectURL() 可以通过图片信息，将信息转换成具体的图片
      this.imgUrl = URL.createObjectURL(file);
      // 将file传给后端
      this.form.img = file;
    },
    // 点击了添加
    submit() {
      let data = {
        ...this.form,
        specsattr: JSON.stringify(this.form.specsattr),
        description: this.editor.txt.html(),
      };
      goodsAdd(data).then((res) => {
        if (res.data.code == 200) {
          successAlert(res.data.msg);
          this.cancel();
          this.reqGoodsList();
          this.reqGoodsTotal();
        } else {
          warningAlert(res.data.msg);
        }
      });
    },
    // 获取一条信息
    getOne(id) {
      goodsInfo({ id: id }).then((res) => {
        // 将请求到的数据赋值给form
        this.form = res.data.list;
        // 给form的specsattr转换成数组类型
        this.form.specsattr = JSON.parse(this.form.specsattr);
        // 根据拿到的一级分类渲染二级分类下拉框
        cateList({ pid: this.form.first_cateid }).then((res) => {
          this.secondArr = res.data.list;
        });
        // 处理图片
        this.imgUrl = this.$pre + this.form.img;
        // 根据拿到商品规格渲染规格属性
        let data = this.specsListData.find(
          (item) => item.id == this.form.specsid
        );
        this.secondAttr = data.attrs;
        // 给form添加id字段，因为后面确定编辑的时候需要用到
        this.form.id = id;
      });
    },
    // 点击了编辑
    edit() {
      let data = {
        ...this.form,
        specsattr: JSON.stringify(this.form.specsattr),
      };
      goodsEdit(data).then((res) => {
        if (res.data.code == 200) {
          successAlert(res.data.msg);
          this.cancel();
          this.reqGoodsList();
        } else {
          warningAlert(res.data.msg);
        }
      });
    },
  },
  mounted() {
    // 页面一进来就要请求一级分类
    this.reqCateList();
    this.reqSpecsList(true);
  },
};
</script>
<style scoped>
/* 1、原生图片上传 */
.imgFile {
  width: 200px;
  height: 200px;
  border: 1px dashed #ccc;
  position: relative;
}
.imgFile h2 {
  line-height: 200px;
  font-size: 50px;
  text-align: center;
  margin: 0 auto;
}
.imgFile input {
  width: 200px;
  height: 200px;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  z-index: 3;
}
.imgFile img {
  width: 200px;
  height: 200px;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}
</style>